package com.beauty.logistics.controller;

import com.beauty.logistics.dto.ShipmentRequest;
import com.beauty.logistics.dto.ShipmentResponse;
import com.beauty.logistics.dto.CarrierResponse;
import com.beauty.logistics.entity.Shipment.ShipmentStatus;
import com.beauty.logistics.result.Result;
import com.beauty.logistics.service.CarrierService;
import com.beauty.logistics.service.ShipmentService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/shipment")
@RequiredArgsConstructor
@Slf4j
public class ShipmentController {
    
    private final ShipmentService shipmentService;
    private final CarrierService carrierService;
    
    @PostMapping
    public Result<ShipmentResponse> createShipment(@Valid @RequestBody ShipmentRequest shipmentRequest) {
        log.info("【物流服务】接收到创建物流单请求: orderId={}, customerId={}, 承运商={}", 
                shipmentRequest.getOrderId(), shipmentRequest.getCustomerId(), shipmentRequest.getCarrierName());
        ShipmentResponse response = shipmentService.createShipment(shipmentRequest);
        log.info("【物流服务】物流单创建成功: 订单号={}, 物流单号={}", response.getOrderId(), response.getTrackingNumber());
        return Result.success(response);
    }
    
    @GetMapping("/{id}")
    public Result<ShipmentResponse> getShipmentById(@PathVariable Long id) {
        return Result.success(shipmentService.getShipmentById(id));
    }
    
    @GetMapping("/tracking/{trackingNumber}")
    public Result<ShipmentResponse> getShipmentByTrackingNumber(@PathVariable String trackingNumber) {
        return Result.success(shipmentService.getShipmentByTrackingNumber(trackingNumber));
    }
    
    @GetMapping("/order/{orderId}")
    public Result<List<ShipmentResponse>> getShipmentsByOrderId(@PathVariable String orderId) {
        log.info("【物流服务】接收到查询订单[{}]物流信息请求", orderId);
        List<ShipmentResponse> shipments = shipmentService.getShipmentsByOrderId(orderId);
        log.info("【物流服务】订单[{}]物流信息查询结果: 找到{}条物流记录", orderId, shipments.size());
        if (!shipments.isEmpty()) {
            for (ShipmentResponse shipment : shipments) {
                log.info("【物流服务】物流单详情: 物流单号={}, 状态={}, 承运商={}", 
                        shipment.getTrackingNumber(), shipment.getStatus(), shipment.getCarrierName());
            }
        }
        return Result.success(shipments);
    }
    
    @GetMapping("/customer/{customerId}")
    public Result<List<ShipmentResponse>> getShipmentsByCustomerId(@PathVariable String customerId) {
        return Result.success(shipmentService.getShipmentsByCustomerId(customerId));
    }
    
    @GetMapping("/status/{status}")
    public Result<List<ShipmentResponse>> getShipmentsByStatus(@PathVariable ShipmentStatus status) {
        return Result.success(shipmentService.getShipmentsByStatus(status));
    }
    
    @GetMapping("/carrier/{carrierName}")
    public Result<List<ShipmentResponse>> getShipmentsByCarrierName(@PathVariable String carrierName) {
        return Result.success(shipmentService.getShipmentsByCarrierName(carrierName));
    }
    
    @GetMapping("/shipping-date")
    public Result<List<ShipmentResponse>> getShipmentsByShippingDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        return Result.success(shipmentService.getShipmentsByShippingDateRange(start, end));
    }
    
    @GetMapping("/delivery-date")
    public Result<List<ShipmentResponse>> getShipmentsByEstimatedDeliveryDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        return Result.success(shipmentService.getShipmentsByEstimatedDeliveryDateRange(start, end));
    }
    
    @GetMapping
    public Result<List<ShipmentResponse>> getAllShipments() {
        return Result.success(shipmentService.getAllShipments());
    }
    
    @PutMapping("/{id}/status")
    public Result<ShipmentResponse> updateShipmentStatus(
            @PathVariable Long id,
            @RequestParam ShipmentStatus status) {
        return Result.success(shipmentService.updateShipmentStatus(id, status));
    }
    
    @PutMapping("/{id}/tracking")
    public Result<ShipmentResponse> updateShipmentTracking(
            @PathVariable Long id,
            @RequestParam String trackingNumber) {
        return Result.success(shipmentService.updateShipmentTracking(id, trackingNumber));
    }
    
    @PutMapping("/{id}/delivery-date")
    public Result<ShipmentResponse> updateShipmentDeliveryDate(
            @PathVariable Long id,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime estimatedDeliveryDate) {
        return Result.success(shipmentService.updateShipmentDeliveryDate(id, estimatedDeliveryDate));
    }
    
    @PutMapping("/{id}/ship")
    public Result<ShipmentResponse> markShipmentAsShipped(
            @PathVariable Long id,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime shippingDate) {
        return Result.success(shipmentService.markShipmentAsShipped(id, shippingDate));
    }
    
    @PutMapping("/{id}/deliver")
    public Result<ShipmentResponse> markShipmentAsDelivered(
            @PathVariable Long id,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime deliveryDate) {
        return Result.success(shipmentService.markShipmentAsDelivered(id, deliveryDate));
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> deleteShipment(@PathVariable Long id) {
        shipmentService.deleteShipment(id);
        return Result.success();
    }
    
    @GetMapping("/carriers")
    public Result<List<Map<String, Object>>> getAvailableCarriers() {
        log.info("【物流服务】接收到获取可用承运商请求");
        
        // 从数据库获取承运商列表
        List<CarrierResponse> carrierResponses = carrierService.getActiveCarriers();
        List<Map<String, Object>> carriers = new ArrayList<>();
        
        for (CarrierResponse carrier : carrierResponses) {
            Map<String, Object> carrierMap = new HashMap<>();
            carrierMap.put("code", carrier.getCode());
            carrierMap.put("name", carrier.getName());
            carriers.add(carrierMap);
        }
        
        // 如果数据库中没有承运商，返回一些默认的
        if (carriers.isEmpty()) {
            Map<String, Object> sf = new HashMap<>();
            sf.put("code", "SF");
            sf.put("name", "顺丰快递");
            carriers.add(sf);
            
            Map<String, Object> zto = new HashMap<>();
            zto.put("code", "ZTO");
            zto.put("name", "中通快递");
            carriers.add(zto);
        }
        
        log.info("【物流服务】返回{}个可用承运商", carriers.size());
        return Result.success(carriers);
    }
} 